<template>
  <el-cascader
    v-bind="$attrs"
    v-on="$listeners"
    popper-class="v-cascader-hide-radio"
    :options="productCategoryTree"
    :props="props"
    :value="selfValue"
    v-loading="loading"
    ref="cascader"
  >
    <div slot-scope="{ node, data }" @click="handleItemChange(node, data)">
      <span>{{ data.category_name }}</span>
    </div>
  </el-cascader>
</template>

<script>
export default {
  props: {
    value: String,
    checkStrictly: {
      type: Boolean,
      default: false,
    },
  },
  model: {
    props: 'value',
    event: 'select',
  },
  data() {
    return {
      loading: false,
      selfValue: [],
      props: {
        value: 'id',
        label: 'category_name',
        checkStrictly: false,
      },
      structure: [2, 2, 2, 3, 3],
    }
  },
  computed: {
    productCategoryTree() {
      return this.$store.getters.productCategoryTree
    },
    totalStructureLength() {
      return this.structure.reduce((p, c) => p + c, 0)
    },
  },
  watch: {
    value: {
      handler: function (val) {
        this.initSelfValue(val)
      },
      immediate: true,
    },
  },
  created() {
    this.$set(this.props, 'checkStrictly', this.checkStrictly)
    this.loading = true
    this.$store.dispatch('getProductCategory').finally(() => {
      this.loading = false
    })
  },
  methods: {
    initSelfValue(val) {
      const res = []
      let totalLength = 0
      for (let len of this.structure) {
        const levelValue = val ? val.substr(totalLength, len) : ''
        const levelNum = Number.parseInt(levelValue, 10)

        if (levelNum <= 0) {
          break
        }

        totalLength += len
        const valueFromStart = val ? val.substr(0, totalLength) : ''
        const pushZero = Array(this.totalStructureLength - totalLength + 1).join('0')
        res.push(`${valueFromStart}${pushZero}`)
      }
      ;[, ...this.selfValue] = res
    },
    handleItemChange(node, _data) {
      // 防止搜索时getCheckedNodes取不到值 cy
      this.$nextTick(() => {
        // const labels = this.getCheckedNodes()
        this.$emit('select', node.value, node.pathLabels)

        if (!node.hasChildren) {
          const { cascader } = this.$refs
          cascader && cascader.toggleDropDownVisible(false)
        }
      })
    },
    // handleChange(val = []) {
    //   const len = val.length
    //   const value = len ? val[len - 1] : ''
    //   // 防止搜索时getCheckedNodes取不到值 cy
    //   this.$nextTick(() => {
    //     const labels = this.getCheckedNodes()
    //     const names = labels.length ? labels[0].pathLabels : []
    //     this.$emit('select', value, names)
    //   })
    // },
    getCheckedNodes() {
      return this.$refs.cascader.getCheckedNodes()
    },
  },
}
</script>

<style scoped></style>
